﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
namespace SAKS.Services.Query
{
    public abstract class PagedQueryOverBase<T>
      : NHibernateQueryBase<PagedResult<T>>,
        IPagedQuery
    {

        public PagedQueryOverBase(ISession session)
            : base(session) { }

        public int First { get; set; }
        public int PageSize { get; set; }

        public override PagedResult<T> Execute()
        {
            var query = GetQuery();
            query.Skip(First).Take(PageSize);
            return Execute(query);
        }

        protected abstract IQueryOver<T, T> GetQuery();

        protected virtual PagedResult<T> Execute(
          IQueryOver<T, T> query)
        {
            var results = query.Future<T>();
            var count = query.ToRowCountQuery().FutureValue<int>();
            return new PagedResult<T>()
            {
                PageOfResults = results,
                TotalItems = count.Value
            };
        }

    }

    public class PagedResult<T>
    {
        public int TotalItems { get; set; }
        public IEnumerable<T> PageOfResults { get; set; }
    }

    public interface IPagedQuery
    {
        int First { get; set; }
        int PageSize { get; set; }
    }

}

